package com.wuyan.locationdog.ui.login


import android.Manifest
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.os.CountDownTimer
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.viewModels
import com.arcsoft.commonbase.R
import com.arcsoft.commonbase.base.BaseBindingActivity
import com.arcsoft.commonbase.ext.afterTextChange
import com.arcsoft.commonbase.ext.customShowLong
import com.arcsoft.commonbase.ext.gone
import com.arcsoft.commonbase.ext.invisible
import com.arcsoft.commonbase.ext.isEmpty
import com.arcsoft.commonbase.ext.isTrimEmpty
import com.arcsoft.commonbase.ext.setPwdVisible
import com.arcsoft.commonbase.ext.textStringTrim
import com.arcsoft.commonbase.ext.visible
import com.arcsoft.commonbase.net.ApiService
import com.arcsoft.commonbase.widgets.ClearEditText
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import com.wuyan.locationdog.BuildConfig
import com.wuyan.locationdog.MainActivity
import com.wuyan.locationdog.databinding.LoginActivityBinding
import com.wuyan.locationdog.help.LoginHelp
import com.wuyan.locationdog.ui.X5WebActivity
import com.wuyan.locationdog.ui.device.DeviceAddActivity
import com.wuyan.locationdog.ui.device.OneDeviceActivity
import com.wuyan.locationdog.viewmodel.LoginViewModel
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.bean.ZxingConfig
import com.yzq.zxinglibrary.common.Constant
import leifu.shapelibrary.ShapeView

class LoginActivity : BaseBindingActivity<LoginActivityBinding>() {

    var longinType: Int = 1
    private var countDownTimer: CountDownTimer? = null
    var isPwdVisible: Boolean = true

    private val mViewModel: LoginViewModel by viewModels()

    override fun initData() {
        BarUtils.transparentStatusBar(this)
        //状态栏白色
        BarUtils.setStatusBarLightMode(this, false)

        binding.apply {

            SpanUtils.with(tvProtocol)
                .append("我已阅读并同意")
                .setForegroundColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_6))
                .append("《使用协议》")
                .setForegroundColor(ColorUtils.getColor(R.color.text_color_selected))
                .setClickSpan(ColorUtils.getColor(R.color.text_color_selected), false) {
                    X5WebActivity.startAction(mActivity, ApiService.BASE_URL + "html/userAgreement.html")

                }
                .append(" ")
                .setForegroundColor(ColorUtils.getColor(com.arcsoft.commonbase.R.color.color_6))
                .append("《隐私政策》")
                .setForegroundColor(ColorUtils.getColor(R.color.text_color_selected))
                .setClickSpan(ColorUtils.getColor(R.color.text_color_selected), false) {
                    X5WebActivity.startAction(mActivity, ApiService.BASE_URL + "html/privacyAgreement.html")

                }
                .create()



            btnTabPwd.setOnClickListener {
                longinType = 1
                loginEnable(etPhone, etPwd)

                tabResetUi()
                tvTabPwd.typeface = Typeface.DEFAULT_BOLD
                tvTabPwdLine.visible()

                phoneLayout.visible()
                pwdLayout.visible()
                deviceCodeLayout.gone()
                msgLayout.gone()
                btnTabPwd.setBackgroundResource(com.wuyan.locationdog.R.mipmap.btntabpwd_bg)

                btnForgetPwd.visible()
                btnRegister.visible()
            }

            btnTabMsg.setOnClickListener {
                longinType = 2
                loginEnable(etPhone, etMsg)

                tabResetUi()
                tvTabMsg.typeface = Typeface.DEFAULT_BOLD
                tvTabMsgLine.visible()

                phoneLayout.visible()
                pwdLayout.gone()
                deviceCodeLayout.gone()
                msgLayout.visible()

                btnTabMsg.setBackgroundResource(com.wuyan.locationdog.R.mipmap.btntabmsg_bg)

                btnForgetPwd.gone()
                btnRegister.gone()
            }

            btnTabDevice.setOnClickListener {
                longinType = 3
                loginEnable(etDeviceCode, etPwd)

                tabResetUi()
                tvTabDevice.typeface = Typeface.DEFAULT_BOLD
                tvTabDeviceLine.visible()


                phoneLayout.gone()
                pwdLayout.visible()
                deviceCodeLayout.visible()
                msgLayout.gone()
                btnTabDevice.setBackgroundResource(com.wuyan.locationdog.R.mipmap.btntabdevice_bg)

                btnForgetPwd.gone()
                btnRegister.visible()
            }

            btnMsg.setOnClickListener {
                msgCountDownTimer()
            }
            //密码可见设置
            btnEye.setOnClickListener {
                etPwd.setPwdVisible(isPwdVisible, it as ImageView)
                isPwdVisible = !isPwdVisible
                etPwd.setSelection(etPwd.text?.length ?: 0)
            }
            btnDeviceCode.setOnClickListener {
                PermissionUtils.permission(Manifest.permission.CAMERA)
                    .callback { isAllGranted, granted, deniedForever, denied ->
                        if (isAllGranted) {
                            goCaptureActivity()
                        } else {
                            customShowLong("请打开相机权限")
                        }
                    }
                    .request()


            }
            btnLogin.setOnClickListener {
                when (longinType) {
                    1 -> {
                        LoginHelp.isDeviceLogin = false

                        onPwdLogin()
                    }

                    2 -> {
                        LoginHelp.isDeviceLogin = false

                        onMsgLogin()
                    }

                    else -> {
                        LoginHelp.isDeviceLogin = true
                        onDeviceLogin()
                    }
                }
//                if (LoginHelp.isDeviceLogin) {
//                    ActivityUtils.startActivity(OneDeviceActivity::class.java)
//
//                } else {
//                    ActivityUtils.startActivity(MainActivity::class.java)
//
//                }

            }
            btnForgetPwd.setOnClickListener {
                val bundle = Bundle()
                bundle.putInt("type", 6)
                ActivityUtils.startActivity(bundle, RegisterActivity::class.java)
            }
            btnRegister.setOnClickListener {
                val bundle = Bundle()
                bundle.putInt("type", 1)
                ActivityUtils.startActivity(bundle, RegisterActivity::class.java)
            }
            onFocusChange(etPhone, phoneTip, phoneStroke)
            onFocusChange(etPwd, pwdTip, pwdStroke)
            onFocusChange(etMsg, msgTip, msgStroke)
            onFocusChange(etDeviceCode, deviceTip, deviceStroke)


            btnTabPwd.callOnClick()
            phoneTip.invisible()
            pwdTip.invisible()
            msgTip.invisible()
            deviceTip.invisible()

            if (BuildConfig.DEBUG) {
                etPhone.setText("18268180705")
                etDeviceCode.setText("lq202")
                etPwd.setText("123456")
            }
            //            btnLogin.isEnabled = false
        }


    }

    override fun observe() {
        mViewModel.loginBean.observe(this) {
            if (LoginHelp.isDeviceLogin) {
                SPUtils.getInstance().put("isDeviceLogin", true)
                SPUtils.getInstance().put("imei", it.content.imei)
                SPUtils.getInstance().put("deviceId", it.content.deviceId)
                LoginHelp.imei = it.content.imei
            } else {
                SPUtils.getInstance().put("isDeviceLogin", false)
            }
            SPUtils.getInstance().put("token", it.content.token)
            if (LoginHelp.isDeviceLogin) {
                if (it.content.dogId.isNullOrEmpty()) {
                    val bundle = Bundle()
                    bundle.putString("scanText", it.content.imei)
                    bundle.putBoolean("isFromLogin", true)
                    ActivityUtils.startActivity(bundle, DeviceAddActivity::class.java)
                    return@observe
                } else {
                    SPUtils.getInstance().put("deviceBindDogSuccess", true)
                    ActivityUtils.startActivity(OneDeviceActivity::class.java)
                }
            } else {
                ActivityUtils.startActivity(MainActivity::class.java)
            }
            finish()
        }
    }

    private fun goCaptureActivity() {
        val intent = Intent(mActivity, CaptureActivity::class.java)

        val config = ZxingConfig()
        config.reactColor = R.color.text_color_selected //设置扫描框四个角的颜色 默认为白色
//        config.frameLineColor = R.color.text_color_selected //设置扫描框边框颜色 默认无色
        config.scanLineColor = R.color.text_color_selected //设置扫描线的颜色 默认白色
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config)
        startActivityForResult(intent, 1111)

    }

    private fun onFocusChange(editText: ClearEditText, tip: TextView, stroke: ShapeView) {
        editText.setFocusChangedListener { view, b ->
            if (b) {
                tip.visible()
                stroke.apply {
                    val color = ColorUtils.getColor(R.color.text_color_selected)
                    tip.setTextColor(color)
                    setShapeStrokeColor(color)
                    setUseShape()
                }
            } else {
                if (editText.isTrimEmpty()) {
                    tip.invisible()
                } else {
                    tip.visible()
                }
                stroke.apply {
                    val color = ColorUtils.getColor(R.color.text_color_unselected)
                    tip.setTextColor(color)
                    setShapeStrokeColor(color)
                    setUseShape()
                }
            }
        }
    }

    private fun LoginActivityBinding.loginEnable(editText1: EditText, editText2: EditText) {
        if (editText1.isTrimEmpty() || editText2.isTrimEmpty()) {
            btnLogin.alpha = 0.4F
            btnLogin.isEnabled = false
        } else {
            btnLogin.alpha = 1F
            btnLogin.isEnabled = true
        }
        editText1.afterTextChange {
            if (editText1.isTrimEmpty() || editText2.isTrimEmpty()) {
                btnLogin.alpha = 0.4F
                btnLogin.isEnabled = false
            } else {
                btnLogin.alpha = 1F
                btnLogin.isEnabled = true
            }
        }
        editText2.afterTextChange {
            if (editText1.isTrimEmpty() || editText2.isTrimEmpty()) {
                btnLogin.alpha = 0.4F
                btnLogin.isEnabled = false
            } else {
                btnLogin.alpha = 1F
                btnLogin.isEnabled = true
            }
        }


    }

    /**
     * 粗体 布局 下划线等切换ui
     */
    private fun LoginActivityBinding.tabResetUi() {
        tvTabPwd.typeface = Typeface.DEFAULT
        tvTabPwdLine.invisible()

        tvTabMsg.typeface = Typeface.DEFAULT
        tvTabMsgLine.invisible()

        tvTabDevice.typeface = Typeface.DEFAULT
        tvTabDeviceLine.invisible()

        btnTabPwd.setBackgroundResource(0)
        btnTabMsg.setBackgroundResource(0)
        btnTabDevice.setBackgroundResource(0)

    }


    private fun LoginActivityBinding.onPwdLogin() {


        if (etPhone.isEmpty()) {
            customShowLong("请输入手机号")
            return
        }
        if (!RegexUtils.isMobileSimple(etPhone.textStringTrim())) {
            customShowLong("请输入正确手机号码")
            return
        }
        if (etPwd.isTrimEmpty()) {
            customShowLong("请输入密码")
            return
        }

        if (!cbProtocol.isChecked) {
            customShowLong("请同意并阅读《使用协议》和《隐私政策》")
            return
        }

        val map = HashMap<String, Any>()
        map["phone"] = etPhone.textStringTrim()
//        map["code"] = etMsg.textStringTrim()
        map["password"] = etPwd.textStringTrim()
        map["type"] = 1

        mViewModel.getLogin(map)
    }

    private fun LoginActivityBinding.onMsgLogin() {
        if (etPhone.isEmpty()) {
            customShowLong("请输入手机号")
            return
        }
        if (!RegexUtils.isMobileSimple(etPhone.textStringTrim())) {
            customShowLong("请输入正确手机号码")
            return
        }
        if (etMsg.isTrimEmpty()) {
            customShowLong("请输入验证码")
            return
        }

        if (!cbProtocol.isChecked) {
            customShowLong("请同意并阅读《使用协议》和《隐私政策》")
            return
        }
        val map = HashMap<String, Any>()
        map["phone"] = etPhone.textStringTrim()
        map["code"] = etMsg.textStringTrim()
//        map["password"] = etPwd.textStringTrim()
        map["type"] = 2

        mViewModel.getLogin(map)
    }

    private fun LoginActivityBinding.onDeviceLogin() {
        if (etDeviceCode.isEmpty()) {
            customShowLong("请输入设备码")
            return
        }

        if (etPwd.isTrimEmpty()) {
            customShowLong("请输入密码")
            return
        }

        if (!cbProtocol.isChecked) {
            customShowLong("请同意并阅读《使用协议》和《隐私政策》")
            return
        }
        val map = HashMap<String, Any>()
        map["imei"] = etDeviceCode.textStringTrim()
        map["password"] = etPwd.textStringTrim()
        mViewModel.deviceLogin(map)
    }

    /**
     * 验证码倒计时
     */
    private fun LoginActivityBinding.msgCountDownTimer() {
        if (etPhone.isEmpty()) {
            customShowLong("请输入手机号")
            return
        }
        if (!RegexUtils.isMobileSimple(etPhone.textStringTrim())) {
            customShowLong("请输入正确手机号码")
            return
        }
        if (countDownTimer == null) {
            countDownTimer = object : CountDownTimer(60 * 1000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    btnMsg.isEnabled = false
                    btnMsg.text = (millisUntilFinished / 1000).toString() + "s后重发"
                    btnMsg.setTextColor(ColorUtils.getColor(R.color.text_color_unselected))
                }

                override fun onFinish() {
                    btnMsg.isEnabled = true
                    btnMsg.text = "获取验证码"
                    btnMsg.setTextColor(ColorUtils.getColor(R.color.text_color_selected))

                }
            }
        }
        countDownTimer?.start()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // 扫描二维码/条码回传
        if (requestCode == 1111 && resultCode == RESULT_OK) {
            if (data != null) {
                val content = data.getStringExtra(Constant.CODED_CONTENT)
                binding.etDeviceCode.setText(content)
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (countDownTimer != null) {
            countDownTimer?.cancel()
        }
    }
}

